package com.sxjh.controller.ht;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.cglib.CglibUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sxjh.common.BaseController;
import com.sxjh.common.ZPage;
import com.sxjh.config.AuthContent;
import com.sxjh.config.Authorization;
import com.sxjh.common.Result;
import com.sxjh.entity.Contract;
import com.sxjh.entity.User;
import com.sxjh.entity.param.ContractAddParam;
import com.sxjh.entity.param.ContractListParam;
import com.sxjh.entity.param.ContractUpdateParam;
import com.sxjh.entity.result.ContractListResult;
import com.sxjh.entity.result.ContractQueryParam;
import com.sxjh.entity.result.ContractQueryResult;
import com.sxjh.service.ContractService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@Api(tags = "合同管理")
@RequestMapping("/contract")
public class ContractController extends BaseController {

  @Autowired
  private ContractService contractService;

  @GetMapping
  @Authorization("ht.contract.lis")
  @ApiOperation("列表")
  Result<ZPage<ContractListResult>> list(@Validated ContractListParam param) {
    IPage<Void> iPage = getIPage(param);
    IPage<ContractListResult> iPage1 = contractService.list(iPage, param);
    ZPage<ContractListResult> zPage = copyPage(iPage1, ContractListResult::new);
    return Result.ok(zPage);
  }

  @GetMapping("/query/{id}")
  @Authorization("ht.contract.lis")
  @ApiOperation("查询单个合同信息")
  Result<Contract> query(@PathVariable("id") Integer id) {
    Contract contract = contractService.getById(id);
    return Result.ok(contract);
  }

  @GetMapping("/query")
  @ApiOperation("合同号查询")
  Result<List<ContractQueryResult>> query(@Validated ContractQueryParam param) {
    LambdaQueryWrapper<Contract> wrapper = new LambdaQueryWrapper<>();
    if (StrUtil.isNotEmpty(param.getContractNumber())) wrapper.like(Contract::getContractNumber, param.getContractNumber());
    wrapper.eq(Contract::getMaterialId, param.getMaterialId());
    wrapper.eq(Contract::getCustomerUserId, param.getCustomerUserId());
    wrapper.select(Contract::getContractNumber);
    // 焦炭只选取子合同
    if (contractService.isJt(param.getMaterialId())) {
      wrapper.eq(Contract::getContractKind, 1);
    }
    List<Contract> list = contractService.list(wrapper);
    return Result.ok(copyList(list, ContractQueryResult::new));
  }

  @PutMapping
  @Authorization("ht.contract.upd")
  @ApiOperation("修改")
  Result<Void> update( @RequestBody ContractUpdateParam param) {
    if (param.getContractKind() == 1) {
      Contract contract = contractService.getOne(new LambdaQueryWrapper<Contract>()
              .eq(Contract::getId, param.getMotherId())
              .eq(Contract::getContractKind, 0));
      if (contract == null) return err("母合同不存在");
//      param.setContractNumber(contract.getContractNumber()+param.getContractNumber());
      param.setMotherId(contract.getId());
      if (param.getStartDate().isBefore(contract.getStartDate())){
        return err("子合同开始时间不能大于母合同开始时间");
      }
      if (contract.getExpiryDate().isBefore(param.getExpiryDate())){
        return err("子合同结束时间不能大于母合同结束时间");
      }
    }
    Contract entity = CglibUtil.copy(param, Contract.class);
    return contractService.updateById(entity)
            ? Result.ok() : Result.err("修改失败");
  }

  @PostMapping
  @Authorization("ht.contract.add")
  @ApiOperation("新增")
  Result<Void> add( @RequestBody ContractAddParam param) {
    // 焦炭合同校验权限，母子合同权限校验
    String msg = verify(param);
    if (msg != null) return err(msg);
    if (param.getContractKind() == 1) {
      Contract contract = contractService.getOne(new LambdaQueryWrapper<Contract>()
              .eq(Contract::getContractNumber, param.getMotherContractNumber())
              .eq(Contract::getContractKind, 0));
      if (contract == null) return err("母合同不存在");
      param.setContractNumber(contract.getContractNumber()+param.getContractNumber());
      param.setMotherId(contract.getId());
      if (param.getStartDate().isBefore(contract.getStartDate())){
        return err("子合同开始时间不能大于母合同开始时间");
      }
      if (param.getExpiryDate().isBefore(contract.getExpiryDate())){
        return err("子合同结束时间不能大于母合同结束时间");
      }
    }
    Contract entity = CglibUtil.copy(param, Contract.class);
    try {
      contractService.save(entity);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      return err("新增失败，合同已存在或其他异常");
    }
    return ok();
  }

  @DeleteMapping("/{id}")
  @Authorization("ht.contract.del")
  @ApiOperation("删除")
  Result<Void> del(@PathVariable Integer id) {
    // 逻辑删除，更新删除人ID,删除时间
    User user = AuthContent.getUser();
    Integer userId = user == null ? 0 : user.getId();
    boolean isD = contractService.update(new LambdaUpdateWrapper<Contract>()
            .eq(Contract::getId, id)
            .set(Contract::getDeletedAt, LocalDateTime.now())
            .set(Contract::getDeletedBy, userId));
    return isD ? Result.ok() : Result.err("删除失败，该合同不存在或其他异常");
  }

  private String verify(ContractAddParam param) {
    // 母子合同校验
    if (param.getContractKind() == 0) {
      // 普通合同
      if (param.getContractCategory() == null) return "合同类别不能为空";
      if (param.getCustomerUserId() == null) return "供应商ID不能为空";
      if (param.getMaterialId() == null) return "产品类别ID不能为空";
      if (param.getStartDate() == null) return "合同起始日期不能为空";
      if (param.getExpiryDate() == null) return "合同终止日期不能为空";
      if (param.getQuantity() == null) return "合同数量不能为空";
      if (StrUtil.isEmpty(param.getStation())) return "到站不能为空";
      if (param.getFreight() == null) return "运费单价不能为空";
      if (param.getAppreciationTax() == null) return "增值税率不能为空";
      if (param.getFreightTax() == null) return "运费税率不能为空";
      if (param.getDepartment() == null) return "签订部门不能为空";
      if (param.getSigner() == null) return "签订人不能为空";
      if (param.getInspection() == null) return "检验验权不能为空";
      if (param.getContractType() == null) return "合同类型不能为空";
      if (param.getPaymentMethod() == null) return "付款方式不能为空";
      if (param.getPaymentType() == null) return "付款类别不能为空";
//      if (param.getMarkup() == null) return "加价不能为空";
      if (param.getComplementaryWay() == null) return "补途不能为空";
      if (StrUtil.isEmpty(param.getAttachment())) return "附件不能为空";
      if (param.getStartDate().isAfter(param.getExpiryDate())) return "起始日期不能大于终止日期";
    } else {
      // 子合同
      if (StrUtil.isEmpty(param.getMotherContractNumber())) return "子合同的母合同号不能为空";
      if (StrUtil.isEmpty(param.getAttachment())) return "子合同的附件不能为空";
      if (param.getStartDate() == null) return "子合同起始日期不能为空";
      if (param.getExpiryDate() == null) return "子合同终止日期不能为空";
    }
    // 焦炭物料额外条件
    if (contractService.isJt(param.getMaterialId()) && param.getContractKind() == 0) {
      if (param.getWater() == null) return "水分不能为空";
      if (param.getDeductWaterType() == null) return "扣水模式不能为空";
      if (param.getAsh() == null) return "灰分不能为空";
      if (param.getSulfur() == null) return "硫分不能为空";
      if (param.getVolatilize() == null) return "挥发分不能为空";
      if (param.getM40() == null) return "M40%不能为空";
      if (param.getM10() == null) return "M10%不能为空";
      if (param.getCsr() == null) return "CSR%不能为空";
      if (param.getCri() == null) return "CRI%不能为空";
      if (param.getFoam() == null) return "焦沫含量%不能为空";
//      if (param.getFoamScale() == null) return "焦沫扣价刻度%不能为空";
      if (param.getFoamDiscount() == null) return "焦沫扣价/吨不能为空";
      if (param.getAshScale() == null) return "灰分扣价刻度%不能为空";
      if (param.getSulfurScale() == null) return "硫分扣价刻度%不能为空";
//      if (param.getVolatilizeScale() == null) return "挥发分扣价刻度%不能为空";
      if (param.getM10Scale() == null) return "M10扣价刻度%不能为空";
      if (param.getM40Scale() == null) return "M40扣价刻度%不能为空";
      if (param.getCsrScale() == null) return "CSR扣价刻度%不能为空";
      if (param.getCriScale() == null) return "CRI扣价刻度%不能为空";
      if (param.getAshDiscount() == null) return "灰分扣价/吨不能为空";
      if (param.getSulfurDiscount() == null) return "硫分扣价/吨不能为空";
//      if (param.getVolatilizeDiscount() == null) return "挥发分扣价/吨不能为空";
      if (param.getM10Discount() == null) return "M10扣价/吨不能为空";
      if (param.getM40Discount() == null) return "M40扣价/吨不能为空";
      if (param.getCsrDiscount() == null) return "CSR扣价/吨不能为空";
      if (param.getCriDiscount() == null) return "CRI扣价/吨不能为空";
    }
    return null;
  }

}